package cn.edu.scau.cmi.zhengweixin.comprehension.controller;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.zhengweixin.comprehension.dao.StudentDAO;
import cn.edu.scau.cmi.zhengweixin.comprehension.dao.TeacherDAO;
import cn.edu.scau.cmi.zhengweixin.comprehension.domain.Student;
import cn.edu.scau.cmi.zhengweixin.comprehension.domain.Teacher;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

	@Autowired
    private TeacherDAO teacherDAO;
	
	@Autowired
    private StudentDAO studentDAO;
	
	@GetMapping("/list")
    public ModelAndView list(ModelAndView mv){
		List<Teacher> list = teacherDAO.findAll();
		mv.addObject("teacherList", list);
		mv.setViewName("teacherList");
		return mv;
	}
	
	@GetMapping("/addPage")
    public ModelAndView addPage(ModelAndView mv){
		mv.setViewName("teacherAdd");
		return mv;
	}
	
	@PostMapping("/add")
    public ModelAndView add(Teacher teacher, ModelAndView mv){
		teacherDAO.save(teacher);
		List<Teacher> list = teacherDAO.findAll();
		mv.addObject("teacherList", list);
		mv.setViewName("teacherList");
		return mv;
	}
	
	@GetMapping("/updatePage")
    public ModelAndView updatePage(@RequestParam Long id, ModelAndView mv){
		Teacher teacher = teacherDAO.findById(id);
		mv.addObject("teacher", teacher);
		mv.setViewName("teacherUpdate");
		return mv;
	}
	
	@PostMapping("/update")
	public ModelAndView update(Teacher teacher, ModelAndView mv) {
		teacherDAO.update(teacher);
		List<Teacher> list = teacherDAO.findAll();
		mv.addObject("teacherList", list);
		mv.setViewName("teacherList");
		return mv;
	}
	
	@GetMapping("/delete")
    public ModelAndView delete(@RequestParam Long id, ModelAndView mv){
		teacherDAO.deleteById(id);
		List<Teacher> list = teacherDAO.findAll();
		mv.addObject("teacherList", list);
		mv.setViewName("teacherList");
		return mv;
	}
	
	@GetMapping("/noTutor")
	public ModelAndView noTutor(@RequestParam Long teacherId, @RequestParam Long studentId, ModelAndView mv){
		Student student = studentDAO.findById(studentId);
		student.setTeacher(null);
		studentDAO.update(student);
		Teacher teacher = teacherDAO.findById(teacherId);
		mv.addObject("teacher", teacher);
		mv.setViewName("tutorList");
		return mv;
	}
	
	@GetMapping("/tutorList")
	public ModelAndView tutorList(@RequestParam Long id, ModelAndView mv){
		Teacher teacher = teacherDAO.findById(id);
		mv.addObject("teacher", teacher);
		mv.setViewName("tutorList");
		return mv;
	}
}
